<template>
  <div>
    <van-nav-bar title="登录" />
    <van-form @submit="onSubmit">
      <van-field
        v-model="mobile"
        label="手机号"
        placeholder="手机号"
        :rules="mrequired"
      />
      <van-field
        v-model="code"
        type="number"
        label="验证码"
        placeholder="验证码"
        :rules="crequired"
      />
      <div style="margin: 16px;">
        <van-button
          round
          block
          :loading="isload"
          type="info"
          native-type="submit"
          >提交</van-button
        >
      </div>
    </van-form>
  </div>
</template>

<script>
import { userlogin } from '@/api/user'
import { mapMutations } from 'vuex'
import { setLocatoken } from '@/utils/localhost'
export default {
  name: 'Login',
  data() {
    return {
      isload: false,
      mobile: '',
      code: '',
      crequired: [
        { required: true, message: '请填写验证码' },
        { pattern: /^\d{6}$/, message: '请填写正确的验证码' }
      ],
      mrequired: [
        { required: true, message: '请填写手机号' },
        { pattern: /^1[3-9]\d{9}$/, message: '请填写正确的手机号' }
      ]
    }
  },
  methods: {
    ...mapMutations('user', ['settoken']),
    async onSubmit() {
      try {
        this.isload = true
        const res = await userlogin(this.mobile, this.code)

        // if (status === 201) {
        //   console.log(data)
        //   // eslint-disable-next-line camelcase
        //   // refresh_token
        //   const { token } = data.data
        setLocatoken(res.data)
        // localStorage.setItem('heima', JSON.stringify(res.data))
        this.settoken(res.data)
        this.$toast.success('登录成功')
        const url = this.$route.query.back
        const flag = this.$route.query.flag
        if (flag) {
          return this.$router.back()
        }
        console.log(url)
        if (url) {
          this.$router.back()
        } else {
          this.$router.push('/')
        }
      } catch (e) {
        this.$toast.fail('登录失败')
      }
    }
  }
}
</script>

<style lang="less" scoped></style>
